import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
import MainLayout from '@/layout/MainLayout.vue'
import { useSysStore } from '@/stores/sys'
import { useAuthStore } from '@/stores/auth'
import { LoginRouterName } from '@/config/global'

let isLoadedRoutes = false // 是否已加载网络路由
/**
 * 默认路由
 */
const defaultRoutes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'login',
    meta: {
      hideTab: true,
      hideMenu: true
    },
    component: () => import('@/views/login/index.vue')
  },
  {
    path: '',
    redirect: '/login'
  }
]

/**
 * 创建路由
 */
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [...defaultRoutes]
})

/**
 * 导航守卫
 */
router.beforeEach(async (to, from) => {
  const sysStore = useSysStore()
  const authStore = useAuthStore()
  // 1、判断是否已加载网络路由
  if (to.name != LoginRouterName && !isLoadedRoutes) {
    // 数据初始化
    await sysStore.initData({ ...to, replace: true })
  }
  // 2、如果有token且去的是登录页，则跳转到默认页
  // if (useToken().getToken() && to.path == '/login') {
  //   router.push({ name: DefaultRouterName })
  // }
  // 3、tab信息
  if (!to.meta.hideTab) {
    authStore.addTagList({ path: to.path, label: to.meta.label as string, name: to.name as string, fullPath: to.fullPath })
  }
  // 4、左侧菜单
  const curPath = to.path.split('/')[1]
  const curMenu = authStore.filterMenuList.find((item) => item.path == curPath)
  authStore.sideList = curMenu?.children || []
  authStore.sideBasePath = '/' + curPath
  // 5、是否隐藏layout
  if (to.meta.hideLayout) {
    sysStore.hideLayout = true
  } else {
    sysStore.hideLayout = false
  }
  return true
})

/**
 * 根据权限注册路由
 */
export function resetRouter(netRoute: RouteRecordRaw[]) {
  // 先清扫原路由中的非默认路由
  router.getRoutes().forEach((item) => {
    let isDefault = false
    // 判断是否是默认路由
    for (let dItem of defaultRoutes) {
      if (dItem.name === item.name) {
        isDefault = true
        break
      }
    }
    // 不是默认路由则移除
    if (!isDefault) {
      item.name && router.removeRoute(item.name)
    }
  })
  // 网络路由-容器
  const ayncRoutes: RouteRecordRaw = {
    path: '',
    component: MainLayout,
    children: netRoute
  }
  // 添加网络路由
  router.addRoute(ayncRoutes)
  // 修改状态为已加载
  isLoadedRoutes = true
}

/**
 * 路由清空
 */
export function clearRouter() {
  isLoadedRoutes = false
}

export default router
